package com.atguigu.flink.chapter05.transform;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author lzc
 * @Date 2023/6/19 08:52
 */
public class SumDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 不同 sensor 的水位和
        env
            .readTextFile("input/sensor.txt")
            .map(new WaterSensorMapFunction())
            .keyBy(new KeySelector<WaterSensor, String>() {
                @Override
                public String getKey(WaterSensor ws) throws Exception {
                    return ws.getId();
                }
            })  // 如果要聚合, 必须先 keyBy
            //            .sum("vc")
//            .max("vc")
//            .min("vc")
            .maxBy("vc", false) // 随着最大值取对应的那个 ts
            .print();
        
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
聚合算子:
1.必须先 keyBy, 再聚合
2.
    sum(position)  元组聚合
    sum(field) pojo 类型的某个属性进行聚会
3. 非分组和聚和字段, 取的是第一个值

----
sum
max min
maxBy minBy
    随着最大或最小取其他值
    
    true: 当出现相同最大或最小的时候,是否取第一个

reduce

    
-------
select
    id,
    sum(vc)
from t
group by id;
 */